/**
 * 定义waterPipe数据访问公共模块
 */
(function(window, angular, undefined){

	var waterCommon = angular.module('waterCommon', ['ui.router']);
	
	/**
	 * 定义httpData对象，用于存放从后台获取过来的数据
	 */
	waterCommon.value("$httpData",{});
	
	/**
	 * 定义queryObj对象，用于存放界面上的查询条件
	 */
	waterCommon.value("$queryObj",{});
	
	/**
	 * 定义queryObj对象，用于存放界面上的查询条件
	 */
	waterCommon.value("$navLocation",{});
	
	/**
	 * 定义viewData对象，用于页面间访问变量用
	 */
	waterCommon.value("$viewData",{});
	
	waterCommon.factory('$waterDataCommon', function($q,$rootScope,$httpData,$queryObj,$viewData,$navLocation,$http,$compile) {
		$waterDataCommon = {	
			/**
			 * 根据表名分页获取表数据，返回的数据根据提供的resultObjName存在httpData对象中
			 */
			getPageRows : function(tableName,resultObjName,queryObj,pageSize,pageIndex,onSuccess,onComplete,onerror,async) { 
				if($httpData[resultObjName] == null){
					$httpData[resultObjName] = {};
				}
				$httpData[resultObjName].isLoading=true
//				queryObj.sessionId = $("#_sessionid").html();
				if(tableName.indexOf(".do") > -1){
					this.getPageRowsByUrl(tableName,resultObjName,queryObj,pageSize,pageIndex,onSuccess,onComplete,onerror,async);
				}
				else{
				}
			},
			getPageRowsByUrl : function(url,resultObjName,queryObj,pageSize,pageIndex,onSuccess,onComplete,onerror,async) { 
				queryObj.WATER_TYPE = getWaterType?getWaterType():'';
				queryObj.pageSizeData = pageSize;
				queryObj.pageIndexData = pageIndex;
//				queryObj.sessionId = $("#_sessionid").html();
				$httpData[resultObjName] = {};
				$httpData[resultObjName].isLoading=true
				var isasync = async == null?"true":async;
				$.ajax({
					url : getBasePath()+url,
					type : 'POST',
					data : queryObj,
					timeout : 35000,
					dataType : 'json',
					success : function(d){
						if(onSuccess){
							onSuccess(d);
						}
						$rootScope.safeApply(function(){
							if (d){
								$httpData[resultObjName] = d;
								$httpData[resultObjName].resultObjName = resultObjName;
								$httpData[resultObjName].tableName = url;
								$httpData[resultObjName].queryObj = queryObj == null?{}:queryObj;
								$httpData[resultObjName].pageSize = pageSize;
								$httpData[resultObjName].pageIndex = pageIndex;
								$httpData[resultObjName].onSuccess = onSuccess;
								$httpData[resultObjName].onComplete = onComplete;
								$httpData[resultObjName].isLoading = false;
							}
						})
						if(onComplete){
							onComplete();
						}
					},
					error : onerror,
					async:isasync
				});
			},
			getModel:function(tableName,key){
				var data = {
					tableName:tableName,
					key:key
				};
				return this.post("/Data/getModelByKey.do",data);
			},
			createModel:function(tableName,data){
				if(!data){
					return;
				}
				data.tableName = tableName;
				return this.post("/Data/Create.do",data);
			},
			updateModel:function(tableName,data){
				if(!data){
					return;
				}
				data.tableName = tableName;
				return this.post("/Data/Update.do",data);
			},
			updateModelWithChild:function(tableName,data){
				if(!data){
					return;
				}
				data.tableName = tableName;
				data.updateChild = true;
				return this.post("/Data/Update.do",data);
			},
			deleteModel:function(tableName,data){
				if(!data){
					return;
				}
				data.tableName = tableName;
				return this.post("/Data/Delete.do",data);
			},
			post:function(url,data,onSuccess,onComplete,onerror,async){
				if(data){
					data.WATER_TYPE = getWaterType?getWaterType():'';
				}
				else{
					data = {
						WATER_TYPE:getWaterType?getWaterType():''
					}
				}
				
				var deferred = $q.defer();
				var promise = deferred.promise;
				var isasync = async == null?"true":async;
				$.ajax({
					url : getBasePath()+url,
					type : 'POST',
					data : data,
					timeout : 35000,
					dataType : 'json',
					async:isasync,
					beforeSend: function(request) {
                        request.setRequestHeader("TOKEN", "crsfToken");
                    },
					success : function(d){
						
						if(d != null && d.data == "error"){
							$.messager.alert("提示",d.msg);
							deferred.reject(d);
							return;
						}
						deferred.resolve(d);
						if(onSuccess){
							onSuccess(d);
						}
						if(onComplete){
							onComplete();
						}
					},
					error : onerror
				});
				return promise;
			},
			firstPage : function(pageDataObj,queryObj){
				if(pageDataObj.pageIndex <= 1){
					return;
				}
				pageDataObj.queryObj = queryObj == null ?pageDataObj.queryObj:queryObj;
				this.getPageRows(pageDataObj.tableName,
						pageDataObj.resultObjName,
						pageDataObj.queryObj,
						pageDataObj.pageSize,
						1,
						pageDataObj.onSuccess,
						pageDataObj.onComplete);
			},
			prePage : function(pageDataObj,queryObj){
				if(pageDataObj.pageIndex <= 1 ){
					return;
				}
				pageDataObj.queryObj = queryObj == null ?pageDataObj.queryObj:queryObj;
				this.getPageRows(pageDataObj.tableName,
						pageDataObj.resultObjName,
						pageDataObj.queryObj,
						pageDataObj.pageSize,
						pageDataObj.pageInfo.pageIndex - 1,
						pageDataObj.onSuccess,
						pageDataObj.onComplete);
			},
			nextPage : function(pageDataObj,queryObj){
				if( pageDataObj.pageIndex >= pageDataObj.pageInfo.pageCount){
					return;
				}
				pageDataObj.queryObj = queryObj == null ?pageDataObj.queryObj:queryObj;
				this.getPageRows(pageDataObj.tableName,
						pageDataObj.resultObjName,
						pageDataObj.queryObj,
						pageDataObj.pageSize,
						pageDataObj.pageInfo.pageIndex + 1,
						pageDataObj.onSuccess,
						pageDataObj.onComplete);
			},
			lastPage : function(pageDataObj,queryObj){
				if(pageDataObj.pageIndex >= pageDataObj.pageInfo.pageCount){
					return;
				}
				pageDataObj.queryObj = queryObj == null ?pageDataObj.queryObj:queryObj;
				this.getPageRows(pageDataObj.tableName,
						pageDataObj.resultObjName,
						pageDataObj.queryObj,
						pageDataObj.pageSize,
						pageDataObj.pageInfo.pageCount,
						pageDataObj.onSuccess,
						pageDataObj.onComplete);
			},
			jsonTostring:function(json){
				var result = "";
				//json.WATER_TYPE = getWaterType?getWaterType():'';
				for(var key in json){
					if(json[key]){
						result += key+"="+encodeURIComponent(json[key])+"&";
					}
				}
				return result;
			},
			Dialog:function(option){
				var url = option.url;
				var html = option.html;
				var title = option.title;
				var height = option.height;
				var width = option.width;
				var scope = option.scope;
				var domId =  option.domId;
				if(url != null){
					 $http({
			    		 	url : url,
							method:'GET'
							}).success(function(data){
								showWindow(data);
							});
				}
				else if(html != null){
					showWindow(html);
				}
				
				function showWindow(contentHtml){
					var window = angular.element("#"+domId);
					var el=$compile(contentHtml)(scope); 
					window.empty();
					window.append(el);
					window.window({title:title,
								height:height,
								width:width,
								modal:true,
								closed:true,
								minimizable:false,
								collapsible:false,
								shadow:true,
								maximizable:false
						});
					window.window("open");
				}				
			},
			AddWktFeaturesToMap:function(wktRecords,symbol,onClick,clear){
				var features = this.ConverWktRecordToFeatures(wktRecords);
				this.AddFeaturesToMap(features,symbol,onClick,clear);
			},
			getDefaultSymbol:function(type){
				var symbol;
				switch (type) {
                case "point":
                    symbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_SQUARE, 10, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255,0,0]), 1), new dojo.Color([0,255,0,0.25]));
                    break;
                case "polyline":
                    symbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255,0,0]), 5);
                    break;
                case "polygon":
                    symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASHDOT, new dojo.Color([255,0,0]), 2), new dojo.Color([255,255,0,0.25]));
                    break;
                case "extent":
                    symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASHDOT, new dojo.Color([255,0,0]), 2), new dojo.Color([255,255,0,0.25]));
                    break;
                case "multipoint":
                    symbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_DIAMOND, 20, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0,0,0]), 1), new dojo.Color([255,255,0,0.5]));
                    break;
				}
				return symbol;
			},
			getDomainByModelName:function(fieldName){
				   var domainArray = eval($("select[ng-model='"+fieldName+"']").attr("data"));
				   var domain={};
				   for(var i=0;i<domainArray.length;i++){
					   if(domainArray[i].attributes == null){
						   continue;
					   }
					   var key = domainArray[i].attributes.S_DOMAINCODE;
					   var value = domainArray[i].attributes.S_DOMAINCAPTION;
					   domain[key] = value;
				   }
				   return domain;
			},
			showSingleLineChar:function(legendName,xData,yData,domId){
				var myChart = echarts.init(document.getElementById(domId)); 
				
				chartOption = {
					    tooltip : {
					        trigger: 'axis'
					    },
					    legend: {
					        data:legendName
					    },
					    toolbox: {
					        show : false
					    },
					    calculable : false,
					    xAxis : [
					        {
					            type : 'category',
					            boundaryGap : false,
					            data : xData
					        }
					    ],
					    yAxis : [
					        {
					            type : 'value'
					        }
					    ],
					    series : [
					        {
					            name:legendName,
					            type:'line',
					            stack: '总量',
					            data:yData
					        }
					    ]
					};
				
				myChart.setOption(chartOption); 
			},
			showMulitLineChar:function(legendNames,xDatas,yDatas,domId,charType,option,dataObject,down,up){
				//添加最大值的刻度
				if(up!=null&&yDatas.length>0) {
					yDatas[0].push(up);
				}
				var myChart = echarts.init(document.getElementById(domId));
				var series = [];
				//判断是否从起点开始,false代表是零刻度开始，设置为true代表离零刻度间隔一段距离
				var headStart=true;
				if(!option){
					option = {};
				}
				
				if(!charType){
					charType = "line";
					headStart=false;
				}
				if(charType=="bar"||legendNames.length>1) {
					option.title+="均值";
				}
				for(var i=0;i<yDatas.length;i++){
					if(!option.shadow && charType == "line" && legendNames.length>1) {
						var serie = {
								name:legendNames[i],
					            type:charType,
					            data:yDatas[i],
					            markLine : {
					                data : [
					                    {type : 'average', name: '平均值'}
					                ]
					            }
							};
					} else {
						var serie={};
						if(up!='' && down=='') {
							serie = {
									name:legendNames[i],
						            type:charType,
						            data:yDatas[i],
						            markLine : {
						                data : [
								            [{name: '阈值上限', value:up , xAxis: 0, yAxis: up},
								             {name: '', xAxis: 100, yAxis: up}]
						                ],
						                color:'red'
						            }
								};
						} else if(up=='' && down!='') {
							serie = {
									name:legendNames[i],
						            type:charType,
						            data:yDatas[i],
						            markLine : {
						                data : [
								            [{name: '阈值下限', value:down , xAxis: 0, yAxis: down},
								                 {name: '', xAxis: 100, yAxis: down}]
							              
						                ]
						            }
								};
						} else if(up!='' && down!='') {
							serie = {
									name:legendNames[i],
						            type:charType,
						            data:yDatas[i],
						            markLine : {
						                data : [
								            [{name: '阈值下限', value:down , xAxis: 0, yAxis: down},
								                 {name: '', xAxis: 100, yAxis: down}],
								            [{name: '阈值上限', value:up , xAxis: 0, yAxis: up},
							                 {name: '', xAxis: 100, yAxis: up}]
							              
						                ]
						            }
								};
						} else {
							serie = {
									name:legendNames[i],
						            type:charType,
						            data:yDatas[i]
								};
						}
					}
					if(option.shadow && yDatas.length == 3 && charType == "line"){
						legendNames=[];
						legendNames.push("最大值");
						legendNames.push("最小值");
						legendNames.push("均值");
						if(i ==0){
							serie.lineStyle={
				                normal: {
				                    opacity: 0
				                }
				            };
							serie.name = '均值';
							serie.stack='confidence-band';
							serie.symbol='none';
						}
						else if(i ==1){
							serie.lineStyle={
					                normal: {
					                    opacity: 0
					                }
					            };
							serie.name = '最小值';
							serie.areaStyle={
				                normal: {
				                    color: '#a5a5a5'
				                }
				            };
							serie.stack='confidence-band';
							serie.symbol='none';
						}
						else{
							serie.name = '最大值';
							serie.lineStyle={
					                normal: {
					                    color:'red'
					                }
					            };
						}
					}
					series.push(serie);
				}
				//判断显示legend
				var legendObject={
			        data:legendNames,
			        x: 'left',                 // 水平安放位置，默认为左对齐，可选为：
                    // 'center' ¦ 'left' ¦ 'right'
                    // ¦ {number}（x坐标，单位px）
                   y: 'top',
			    };
				if(getWaterType()=='1'){
					legendObject={data:legendNames};
				}
				chartOption = {
						title : {
					        text: option.title,
					        textStyle:{
					            fontSize:14
					        }
						},
						tooltip: {
				            trigger: 'axis',
				            axisPointer: {
				                animation: false
				            }
				        },
					    legend: legendObject,
					    toolbox: {
					        show : true,
					        feature : {
					            //mark : {show: true},
					        	dataZoom: {
					        		show: true 
					            },
					            restore : {show: true},
					            saveAsImage : {show: true}
					        }
					    },
					    
					    calculable : false,
					    xAxis : [
					        {
					            type : 'category',
					            boundaryGap : headStart,
					            data : xDatas,
					            axisLabel:{
					                 //X轴刻度配置
					                 interval:'auto', //0：表示全部显示不间隔；auto:表示自动根据刻度个数和宽度自动设置间隔个数
					                 rotate:70
					            }
					        }
					    ],
					    grid: { // 控制图的大小，调整下面这些值就可以，
				             x: 70,
				             x2: 100,
				             y2: 150,// y2可以控制 X轴跟Zoom控件之间的间隔，避免以为倾斜后造成 label重叠到zoom上
				         },
					    yAxis : [
					        {
					            type : 'value'
					        }
					    ],
					    series : series
					};
				if(option.shadow){
					chartOption.tooltip.formatter = function(params){
						var value = Math.round(params[0].value*100)/100;
						var max = params[1].value;
						var min = Math.round(params[2].value*100)/100;
						var date_text = params[0].name;
						max = Math.round((max + value)*100)/100;
						var text = "最小值:"+value+"<br />";
						text += "最大值:"+max+"<br />";
						text += "均值:"+min+"<br />";
						text += "日期:"+date_text+"<br />";
		                return text;
					}
				}
				
				myChart.setOption(chartOption);
                return myChart;
			},
			websockets:[],
			listenServer:function(url,onMessage){
				// 污染源：
				//  实时数据 realTimeData
				//  命令结果 orderStatus
				//  站点状态 stationInfo
				
				var me = this;
				var websockets = me.websockets;
				
				for(var i=0;i<websockets.length;i++){
					var ws = websockets[i];
					ws.close();
				}
				
				url = getWebSocketPath() + url;
				var websocket;				
				try {
					websocket = new WebSocket(url);
					me.websockets.push(websocket);
				} catch (e) {
					return null;
				}
			  
			   websocket.onopen = function(){ 
				   console.log(url+",监听打开") 
			   };
			   websocket.onmessage = function(evn){
				   console.log(url+"收到消息："+evn.data);
				   if(onMessage){
					   var data = null;
					   try {
						   eval("data=" + evn.data);
						} catch (e) {
							
						}
					   
					   onMessage(data); 
				   }
			   };
			   websocket.onerror = function(evn){
				   console.log(url+",监听出错")
			   };
			   websocket.onclose = function(){
				   console.log(url+",连接关闭")
			   };
			   return websocket;
			},
			//判断日期大小，只有日期
			judgmentDate : function(startDate,endDate){
				if(startDate.length>0&&endDate.length>0){   
	                   var startDateTemp = startDate.split(" ");   
	                   var endDateTemp = endDate.split(" ");   
	                   var arrStartDate = startDateTemp[0].split("-");   
	                   var arrEndDate = endDateTemp[0].split("-");   
	                    var allStartDate = new Date(arrStartDate[0],arrStartDate[1],arrStartDate[2]);   
	                    var allEndDate = new Date(arrEndDate[0],arrEndDate[1],arrEndDate[2]);   
	                    if(allStartDate.getTime()>allEndDate.getTime()){   
	                        return false;   
	                    }   
	                }   
	                return true; 
			},
		   //判断日期大小,包含时间 	
			judgmentDateTime : function(startDate,endDate){
				if(startDate.length>0&&endDate.length>0){   
	                   var startDateTemp = startDate.split(" ");   
	                   var endDateTemp = endDate.split(" ");   
	                   var arrStartDate = startDateTemp[0].split("-");   
	                   var arrEndDate = endDateTemp[0].split("-");   
	                   var arrStartTime = startDateTemp[1].split(":");   
	                   var arrEndTime = endDateTemp[1].split(":");   
	                    var allStartDate = new Date(arrStartDate[0],arrStartDate[1],arrStartDate[2],arrStartTime[0],arrStartTime[1],arrStartTime[2]);   
	                    var allEndDate = new Date(arrEndDate[0],arrEndDate[1],arrEndDate[2],arrEndTime[0],arrEndTime[1],arrEndTime[2]);   
	                    if(allStartDate.getTime()>allEndDate.getTime()){   
	                        return false;   
	                    }   
	                }   
	                return true; 
			}
		};
		
		$rootScope.httpData = $httpData;
		$rootScope.queryObj = $queryObj;
		$rootScope.viewData = $viewData;
		$rootScope.navLocation = $navLocation;
		
		return $waterDataCommon;
	});
	
}(window, angular));